package com.trade.core.context;


import com.trade.core.utils.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sven.wang
 * @version 2021/12/8 17:48
 * @Description: 交易构造上下文容器
 */
public class TradeContextHandler {

    /**
     * 上下文
     */
    private static ThreadLocal<Map<String, Object>> tradeThreadLocal = InheritableThreadLocal.withInitial(HashMap::new);

    TradeContextHandler(){

    }

    public static void remove() {
        tradeThreadLocal.remove();
    }


    public static void set(String key, Object value) {
        Map<String, Object> map;
        if ((map = (Map) tradeThreadLocal.get()) == null) {
            map = new HashMap();
            tradeThreadLocal.set(map);
        }

        ((Map)map).put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map;
        if ((map = (Map) tradeThreadLocal.get()) == null) {
            map = new HashMap();
            tradeThreadLocal.set(map);
        }

        return ((Map)map).get(key);
    }

    /**
     * 获取上下文所有的内容
     */
    public static Map<String, Object> getMap() {
        Map<String, Object> map = (Map) tradeThreadLocal.get();
        if (map == null) {
            map = new HashMap();
            tradeThreadLocal.set(map);
        }
        return map;
    }

    /**
     * 批量设置上下文内容
     * @param oldMap oldMap
     */
    public static void putAll(Map<String, Object> oldMap){
        if(CollectionUtils.empty(oldMap)){
            return;
        }
        Map<String, Object> map = (Map) tradeThreadLocal.get();
        if (map == null) {
            map = new HashMap();
            tradeThreadLocal.set(map);
        }
        map.putAll(oldMap);
    }

}
